package com.graduation.lastproject.controller.business.businessBasicActive;

import com.graduation.lastproject.entity.Business;
import com.graduation.lastproject.entity.HotelInfo;
import com.graduation.lastproject.service.business.businessBasicActive.BusinessService;
import com.graduation.lastproject.util.shiro.LoginsToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping("/business")
public class BusinessControl {

    @Autowired
    BusinessService businessService;
    @Value("${spring.fileupload.destination}")
    private String destination;
    @Value("${login.business}")
    private String BusinessType;

    @RequestMapping(value = "{page}")
    public String topages(@PathVariable String page, HttpServletRequest request, HttpServletResponse response){
        if(page.equals("register")){
            request.setAttribute("type","注册");
        }
        if(page.equals("update")){
            Business businessInfo = (Business) request.getSession().getAttribute("businessInfo");
            System.err.println("商家信息:"+businessInfo);
            request.setAttribute("entry",businessInfo);
            request.setAttribute("type","更新");
            return "/business/register";
        }
        if(page.equals("uploadInfo")){
            Business businessInfo = (Business) request.getSession().getAttribute("businessInfo");
            request.setAttribute("businessName",businessInfo == null ? "" : businessInfo.getBphone());
            if(businessInfo!=null){     //如果获取到数据 前台录入则提示不可重复录入
                HotelInfo hotelInfo=businessService.getHotelInfoByBphone(businessInfo.getBphone());
                if(hotelInfo != null){
                    request.setAttribute("hotelInfoId",hotelInfo.getId());
                }else {
                    request.setAttribute("hotelInfoId","test");
                }
            }
        }
        if(page.equals("uploadInfo") ||page.equals("uploadInfoEdit") || page.equals("uploadPhotoEdit") || page.equals("business_bookorder") || page.equals("business_review")|| page.equals("business_totalInPrice")){
            Business businessInfo = (Business) request.getSession().getAttribute("businessInfo");
            request.setAttribute("businessName",businessInfo == null ? "" : businessInfo.getBphone());  //保存登录人电话 前端页面判断需要
            if(businessInfo!=null){
                HotelInfo hotelInfo=businessService.getHotelInfoByBphone(businessInfo.getBphone());
                request.setAttribute("hotelInfo",hotelInfo);
            }
        }
        String pages="business/"+page;
        return pages;
    }

    //商家信息注册
    @RequestMapping(value = "/bregister",method = RequestMethod.POST)
    @ResponseBody
    public  Object bregister(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>() ;
        Map<String,Object> map=parameters(request);
        //判断电话是否存在
        boolean flag=businessService.getBusinessPhone(map.get("bphone").toString());
        if(!flag){
            int i=businessService.insertBusinessInfo(map);
            result.put("msg",i == 1 ? "保存成功" : "保存失败");
        }else {
            result.put("msg","电话已被注册,请重新输入电话");
        }
        return result;
    }


    //商家登录
    @RequestMapping(value = "/blogined",method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        //1 获取Subject
        Subject subject= SecurityUtils.getSubject();
       /* if(!subject.isAuthenticated()){*/
            //创建令牌，封装用户数据
            LoginsToken token=new  LoginsToken(request.getParameter("brealname"),request.getParameter("bpassword"),BusinessType);;
        try {
            subject.login(token);
            String businessState=((Business)request.getSession().getAttribute("businessInfo")).getState()+"";
            String businessReason=((Business)request.getSession().getAttribute("businessInfo")).getReason()+"";
            if(businessState.equals("1")){
                request.getSession().removeAttribute("business");
            }
            result.put("msg","登录成功");
            result.put("businessState",businessState);
            result.put("businessReason",businessReason);
            return result;
        }catch (UnknownAccountException e){
            result.put("msg","登录名未注册,登录失败");
            return result;
        }catch (IncorrectCredentialsException e){
            result.put("msg","密码错误,登录失败");
            return result;
        }

    }

    //商家信息修改
    @RequestMapping(value = "/bupdate")
    @ResponseBody
    public Object bupload(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>() ;
        Map<String,Object> map=parameters(request);
        /*修改商家bphone还要级联更改hotel_info 表  当初用商家id关联hotel_info 它不香吗 不就不用改了吗*/
        if(!map.get("bphone").toString().equals(map.get("oldbphone").toString())){
            Map<String,Object> map1=new HashMap<>() ;
            String id=map.get("id").toString();
            String Newbphone=map.get("bphone").toString();
            map1.put("id",id);
            map1.put("Newbphone",Newbphone);
            businessService.updateHotelInfoBphone(map1);
        }
        int i=businessService.uploadBusinessInfo(map);
        result.put("msg",i == 1 ? "修改成功" : "修改失败");
        logout();
        return  result;
    }

    //商家退出
    @RequestMapping("/blogout")
    public String logout(/*HttpServletRequest request*/) {
        /*Subject subject = SecurityUtils.getSubject();//取出当前验证主体
        System.err.println("subject:"+subject);
        if (subject != null) {
            subject.logout();//不为空，执行一次logout的操作，将session全部清空
        }*/
     /*   request.getSession().removeAttribute("business");
        request.getSession().removeAttribute("businessInfo");*/
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.removeAttribute("businessInfo");
        session.removeAttribute("business");
        return "/business/index"; //返回到系统主页
    }

    //上传酒店数据信息
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public Object uplodeFile(HttpServletRequest request,Model model){
        Map<String,Object> result=new HashMap<>();
        Map<String,Object> map=parameters(request);
        Map<String, String[]> map1 = request.getParameterMap();
        String serviceFacilities=Arrays.toString((String[])map1.get("serviceFacilities"));
        String hotelRoomType=Arrays.toString((String[])map1.get("hotelRoomType"));
       /* String[] serviceFacilities=(String[])map1.get("serviceFacilities");
        String[] hotelRoomType=(String[])map1.get("hotelRoomType");*/
        map.put("serviceFacilities",serviceFacilities);
        map.put("hotelRoomType",hotelRoomType);
        String uuid = UUID.randomUUID().toString();
        map.put("id",uuid);
        int i=businessService.insertInfo1(map);
        if(i!=1) {
            model.addAttribute("msg","操作执行失败，请重新填写信息");
            return "uploadFile";
        }
        String[] hotelAllRoomType={"3","4"};
        String[] hotelRoom=(String[])map1.get("hotelRoomType");

        // HashMap key值 不可重复 Key值和value值都可以为null
        HashMap<String, Object> mapAll = new HashMap<String, Object>();

        // 数组hotelRoom中的元素放入Map中
        for (String string1 : hotelRoom) {
            mapAll.put(string1, string1);
        }
        // 用数组B元素做为Key来取值，如为NULL则mapAll不存在
        for (String string2 : hotelAllRoomType) {
            Object j = mapAll.get(string2);
            if (j == null) {
                if(string2.equals("3")){
                    request.setAttribute("sw","隐藏");
                }else if(string2.equals("4")){
                    request.setAttribute("ql","隐藏");
                }
            }else {
                if(string2.equals("3")){
                    request.setAttribute("sw","显示");
                }else if(string2.equals("4")){
                    request.setAttribute("ql","显示");
                }
            }
        }
        request.setAttribute("id",uuid);
        return "business/uploadPhoto";
    }


    //上传酒店图片信息
    @RequestMapping(value = "/uploadPhoto",method = RequestMethod.POST)
    public Object uplodePhoto(HttpServletRequest request, @RequestParam("files") MultipartFile[] files) throws IOException {
               /*Map<String,Object> result= new HashMap<>();*/
               String id=request.getParameter("id");
               String msg = "";
               int i=0;
                if(null != files && files.length>0){
                    for(MultipartFile file : files){
                        // 测试MultipartFile接口的各个方法
                        System.out.println("文件组件名称Name=" + file.getName());
                        System.out.println("文件原名称OriginalFileName=" + file.getOriginalFilename());
                        System.out.println("文件大小Size=" + file.getSize() + "byte or " + file.getSize()/1024 + "KB");
                        msg=saveInfo(file,destination,id,i);
                        i++;      //i [0,1,2,3,4} 判断
                    }
                    /*request.setAttribute("msg","上传成功");*/
                    return "redirect:http://localhost:8080/business/uploadInfoEdit";
                }else {
                   /* request.setAttribute("msg","上传失败");*/
                    return "redirect:http://localhost:8080/business/uploadInfo";
                }
    }


    //图片保存
    private String saveInfo(MultipartFile file, String destination,String id,int time) throws IOException {
        // 获取上传的文件名称，并结合存放路径，构建新的文件名称
        String filename = file.getOriginalFilename();
        String fileExtName = String.valueOf(System.currentTimeMillis());
        String filepathName=fileExtName+"_"+filename;
        File filepath = new File(destination, filepathName);

        // 判断路径是否存在，不存在则新创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        // 将上传文件保存到目标文件目录
        file.transferTo(filepath);
        String path="D:\\\\file\\\\hotelPicInfo"+"\\\\"+filepathName;
        String realPath=path.replace("\\\\", "/");
        Map<String,Object> info=new HashMap<>();
        info.put("picLocation",realPath);
        info.put("id", id);
        info.put("time",time);
        if(time == 0){
            int i=businessService.insertPicInfo(info);
        }else {
            int q=businessService.updatePicInfo(info);
        }
        return "成功";

    }

    /** request转map */
    private final Map<String, Object> parameters(HttpServletRequest request) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        if (request != null) {
            Enumeration<String> keys = request.getParameterNames();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                try {
                    parameters.put(key, request.getParameter(key));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return parameters;
    }
}
